package AnnotationCache.core;


import AnnotationCache.Run.Model;
import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.runtime.RuntimeSchema;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * Created by wangyg 
 * on 2017/7/31 17:21
 */
public class DefaultHandler<T> {

	private final JedisPool jedisPool;
	private String ip ;
	private int port ;
	private String password="A07L22R07y10qL";
	private int db=0;

	private RuntimeSchema<Model> schema = RuntimeSchema.createFrom(Model.class);

	public DefaultHandler(String ip,int port) {
		this.jedisPool = new JedisPool(new GenericObjectPoolConfig(),ip, port,3000,password);

	}

	public T get(String value) {

		try {
			Jedis jedis = jedisPool.getResource();
			try {
				String key = "CacheKey/" + value;
				byte[] bytes = jedis.get(key.getBytes());
				if (bytes != null) {
					Model model = schema.newMessage();
					ProtostuffIOUtil.mergeFrom(bytes, model, schema);
					return (T) model;
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				jedis.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	public String set(String value, Model obj) {
		String setex = null;
		try {
			setex = null;
			Jedis jedis = jedisPool.getResource();
			try {
				String key = "CacheKey/" + value;

				Model model = schema.newMessage();
				byte[] bytes1 = ProtostuffIOUtil
						.toByteArray(obj, schema, LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));
				int timeOut = 60*60;
				setex = jedis.setex(key.getBytes(), timeOut, bytes1);

			} catch (Exception e) {
				e.printStackTrace();
			}finally {
				jedis.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return setex;
	}

	public String keyGenerator() {
		return null;
	}
}
